<?php

namespace app\admin\controller;

use app\common\controller\Backend;

class Index extends Backend
{
    //设置属性 -->不需要登录方法名
    protected $NoNeedLogin = ['login'];
    public function index()
    {
        $navTitle = '后台首页';
        return $this->fetch('', [
            'navTitle' => $navTitle
        ]);
    }

    //登录
    public function login()
    {
        $LoginAdmin = !empty(cookie('LoginAdmin')) ? cookie('LoginAdmin') : '';
        if ($LoginAdmin) {
            $adminList = model('Admin')->select();

            $adminid = 0;
            foreach ($adminList as $item) {
                $val = md5($item['id'] . $item['salt']);
                if ($LoginAdmin == $val) {
                    $adminid = $item['id'];
                    break;
                }
            }

            $admin = model('Admin')->find($adminid);

            if (!$admin) {
                cookie('LoginAdmin', null);
                $this->error('非法登录', url('admin/index/login'));
            }

            if (!empty($admin['state']) && $admin['state'] != 1) {
                cookie('LoginAdmin', null);
                $this->error('管理员已禁用');
            }

            $this->success('您已登录了，无须重复登录', url('admin/index/index'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->param();

            if (!captcha_check($params['captcha'])) {
                $this->error('验证码错误');
            }

            $admin = model('Admin')->where('username', $params['username'])->find();

            if (!$admin) {
                $this->error('管理员不存在');
            }

            $password = md5($params['password'] . $admin['salt']);
            if ($password != $admin['password']) {
                $this->error('密码错误');
            }

            //判断管理员的状态
            if (!empty($admin['state']) &&  $admin['state'] == 0) {
                $this->error('该管理员已经被禁用');
            }

            if ($params['rememberme'] == 1) {
                cookie('LoginAdmin', md5($admin['id'] . $admin['salt']), 5 * 24 * 3600 + time());
            } else {
                cookie('LoginAdmin', md5($admin['id'] . $admin['salt']));
            }

            $this->success('登录成功', url('admin/index/index'));
        }
        //动态使用模板布局
        $this->view->engine->layout(false);
        return $this->fetch();
    }
}
